package org.totoro.cglib;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author YHL
 * @version V1.0
 * @Description: cglib 测试
 * @date 2018-11-15
 */
public class CglibTest implements MethodInterceptor {


    private static final Logger LOGGER = LoggerFactory.getLogger(CglibTest.class);

    private Object targetObject;

    public Object getProxyObject(Object object) {

        this.targetObject = object;

        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(this);
        enhancer.setSuperclass(targetObject.getClass());
        enhancer.setInterfaces(targetObject.getClass().getInterfaces());

        return enhancer.create();
    }

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        LOGGER.debug("intercept method{}", method.getName());

        Object invoke = methodProxy.invoke(targetObject, objects);

        return invoke;
    }
}
